package com.android.aqq;

import java.util.Calendar;
import java.util.Iterator;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.android.aqq.bean.ChatState;
import com.android.aqq.bean.QQBuddy;
import com.android.aqq.bean.QQGroup;
import com.android.aqq.bean.QQMessage;
import com.android.aqq.util.Utils;

import edu.tsinghua.lumaqq.qq.Util;
import edu.tsinghua.lumaqq.qq.events.QQEvent;
import edu.tsinghua.lumaqq.qq.packets.in.ReceiveIMPacket;

public class ChatWindowActivity extends Activity {
	private ChatState chatState; 
	private QQBuddy buddy;
	private TableLayout mTableLayout;
	private ScrollView mScrollView;
	private int positon = 0;
	private Menu mMenu;
	private EditText mEditText;
	private int myQQ;
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat_window);
		
		Intent intent = getIntent();
		buddy = (QQBuddy)intent.getSerializableExtra("FRIEND");
		myQQ = intent.getIntExtra("MYQQ", 0);
		
		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // 取消通知栏通知
        nm.cancel(aQQActivity.NOTIFICATION_FRIEND_CHAT);
		
		if (aQQActivity.mChatStateMap == null || aQQActivity.user == null || !aQQActivity.user.isLoggedIn()) {
			finish();
			return;
		} 
		
		chatState = aQQActivity.mChatStateMap.get(buddy.getQQ());
		if (chatState == null) { //会话状态不存在
			finish();
			return;
		}
		chatState.setBuddy(buddy);
		chatState.resetNewMessageCount();
		
		//设置标题
		setTitle("与" + buddy.toString() + "聊天");
		
		
		//绑定handler
		aQQActivity.removeHandler(buddy.getQQ());
		aQQActivity.bindHandler(buddy.getQQ(), mHandler);
		
		mTableLayout = (TableLayout)findViewById(R.id.TableLayout02);
		mScrollView = (ScrollView)findViewById(R.id.ScrollView01);
		
		final Button sendButton =(Button) findViewById(R.id.ButtonSend);
		mEditText = (EditText) findViewById(R.id.TextSend);
		sendButton.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				if (mEditText.getText().length() > 0) {
					sendMessage();
				}
			}
		});
		
		Iterator<QQMessage> iterator = chatState.getMessageQueue().iterator();
		while(iterator.hasNext()) {
			QQMessage message = iterator.next();
			if (message.getSender() == myQQ) {
				insertChat(message.getMessage(), true);
			} else {
				insertChat(message.getMessage().replaceAll(buddy.getQQ() + "：", buddy.toString() + "："), false);
			}
			
		}
	}
	
	private void sendMessage() {
		String message = mEditText.getText().toString();
		aQQActivity.client.im_Send(buddy.getQQ(), Util.getBytes(message));
		message = "我：["+ DateFormat.format("kk:mm", Calendar.getInstance()) + "]\n" + message;
		insertChat(message, true);
		mEditText.setText("");
		chatState.addMessage(myQQ, message, false);
	}
	
	private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	switch(msg.what) {
        	case QQEvent.IM_RECEIVED:
        		QQEvent event = (QQEvent) msg.obj;
        		ReceiveIMPacket im = (ReceiveIMPacket) event.getSource();
        		String message = buddy.toString() + "：["+ DateFormat.format("kk:mm", im.normalHeader.sendTime) + "]\n" + Utils.parseIMMessage(ChatWindowActivity.this, im.normalIM.messages);
				insertChat(message, false);
        		break;
        	case -1:
        		finish();
        		break;
        	}
        }
	};
	
	private void insertChat(String message, boolean me) {
		TextView v = new TextView(ChatWindowActivity.this);
		v.setText(message.replaceAll("\r","\n"));
		TableRow row = new TableRow(ChatWindowActivity.this);
		TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
//		layoutParams.span = 2;
		layoutParams.column=1;
		v.setLayoutParams(layoutParams);
		v.setTextSize(18);
		v.setPadding(3, 3, 3, 3);
		v.setSingleLine(false);
		if (me) {
			row.setBackgroundDrawable(getResources().getDrawable(R.drawable.chat_text_highlight_background));
		} else {
			row.setBackgroundDrawable(getResources().getDrawable(R.drawable.chat_text_background));
		}
		v.setTextColor(getResources().getColor(android.R.color.black));
		row.addView(v);
		mTableLayout.addView(row, positon);
		mHandler.post(scrollToBottom);
		positon ++;
	}
	
	private Runnable scrollToBottom = new Runnable() {  
        public void run() {  
            int off = mTableLayout.getMeasuredHeight() - mScrollView.getHeight();  
            if (off > 0) {  
                mScrollView.scrollTo(0, off);  
            }                         
        }  
	};
	
	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
		chatState.resetNewMessageCount();
	}

	@Override
	protected void onStart() {
		super.onStart();
	} 
 
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
    	 mMenu = menu;
         
         MenuInflater inflater = getMenuInflater();
         inflater.inflate(R.menu.menu_chat, menu);
         
         return true;
    }
    
    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
        switch (item.getItemId()) { 
        	case R.id.menu_end_conversation:
        		aQQActivity.mChatStateMap.remove(buddy.getQQ());
        		setResult(RESULT_CANCELED);
        		finish();
	            break;
        	case R.id.menu_change_conversation:
        		Intent intent = new Intent(ChatWindowActivity.this, ChatDashboardActivity.class);
        		intent.putExtra("CHAT_ID", buddy.getQQ());
        		startActivityForResult(intent, 3);
	            break;
        }
        return super.onOptionsItemSelected(item);
    }
    
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 3) {
			if (resultCode == RESULT_OK) {
				int id = data.getIntExtra("CHAT_ID", 0);
				if (id!=0) {
					ChatState chat = aQQActivity.mChatStateMap.get(id);
					if (chat.getType() == 1) {
						QQBuddy buddy = chat.getBuddy();
						startActivity(new Intent(this, ChatWindowActivity.class).putExtra("FRIEND", buddy).putExtra("MYQQ", myQQ));
						finish();
					} else {
						QQGroup group = chat.getQQGroup();
						startActivity(new Intent(this, GroupChatWindowActivity.class).putExtra("QQ_GROUP", group).putExtra("MYQQ", myQQ));
						finish();
					}
					
				}
			}
        }
	}
	
}
